﻿using System.Drawing;
using ClosedXML.Excel;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ProduceBasicData.Domain.FactoryModeling;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Controllers
{
    /// <summary>
    /// 导出控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ExportController : ControllerBase
    {
        private readonly IBaseRespository<ProcessModel> processRepo;

        public ExportController(IBaseRespository<ProcessModel> processRepo)
        {
            this.processRepo = processRepo;
        }

        /// <summary>
        /// 导出工序维护
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult ExportCraftMaintain()
        {
            try
            {
                // 1. 从数据源获取工艺维护数据
                var craftMaintainList = processRepo.GetAll(); // 假设的服务方法

                // 检查是否有数据可导出
                if (craftMaintainList == null || !craftMaintainList.Any())
                {
                    return NotFound("没有可导出的工艺维护数据");
                }

                // 2. 创建Excel工作簿
                using (var workbook = new XLWorkbook())
                {
                    var worksheet = workbook.Worksheets.Add("工艺维护数据");

                    // 3. 设置表头（根据工艺维护的实际字段定制）
                    var headers = new string[]
                    {
        "维护编码", "维护名称", "维护类型", "报工模式", "维护描述","创建人","创建时间"
                    };

                    // 添加表头并设置样式
                    for (int i = 0; i < headers.Length; i++)
                    {
                        var cell = worksheet.Cell(1, i + 1);
                        cell.Value = headers[i];
                        cell.Style.Font.Bold = true;
                        cell.Style.Fill.BackgroundColor = XLColor.FromHtml("#4472C4");
                        cell.Style.Font.FontColor = XLColor.White;
                        cell.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                    }

                    // 4. 填充数据
                    int row = 2; // 从第二行开始填充数据
                    foreach (var craft in craftMaintainList)
                    {
                        // 填充工艺维护数据（根据实际属性调整）
                        worksheet.Cell(row, 1).Value = craft.Processcode;
                        worksheet.Cell(row, 2).Value = craft.Processname;
                        worksheet.Cell(row, 3).Value = craft.ProcessType;
                        worksheet.Cell(row, 4).Value = craft.Reporting;
                        worksheet.Cell(row, 5).Value = craft.Processdesc;
                        worksheet.Cell(row, 6).Value = craft.CreateName;
                        worksheet.Cell(row, 7).Value = craft.CreateTime;

                        // 设置日期格式

                        if (craft.UpdateTime.HasValue)
                            worksheet.Cell(row, 7).Style.DateFormat.Format = "yyyy-MM-dd HH:mm";
                        row++;
                    }

                    // 5. 自动调整列宽
                    worksheet.Columns().AdjustToContents();

                    // 6. 添加筛选功能
                    worksheet.Range(1, 1, 1, headers.Length).SetAutoFilter();

                    // 7. 冻结首行
                    worksheet.SheetView.Freeze(1, 0);

                    // 8. 准备内存流
                    using (var stream = new MemoryStream())
                    {
                        workbook.SaveAs(stream);
                        stream.Position = 0;

                        // 9. 返回Excel文件
                        return File(
                            stream.ToArray(),
                            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                            $"工序维护数据_{DateTime.Now:yyyyMMddHHmmss}.xlsx"
                        );
                    }
                }
            }
            catch (Exception ex)
            {
                // 记录异常日志
                // _logger.LogError(ex, "导出工艺维护数据时发生错误");
                return StatusCode(500, $"导出数据时发生错误: {ex.Message}");
            }
        }
    }
}
